/**
 * this files imports or updates exisiting entries with pubchem compound properties
 */

import edu.ucdavis.genomics.metabolomics.binbase.connector.references.ncidb.NCIDBSDFResolver
import org.apache.log4j.Logger
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.InchFinder
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.SdfToInchi
import compound.repository.entries.Compound
import util.CompoundHelper

//configuration file
def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

Logger logger = Logger.getLogger("ImportNCI")

logger.info("starting import/update of the nci compound data")


String tempDir = config.files.ncidb.rawdata

FileHelper.workOnDir(tempDir, {File file ->
  NciInchiSubstance sub = new NciInchiSubstance()
  SdfToInchi.sdfToInchi(new FileInputStream(file), sub)

}, logger, ".sdf")

class NciInchiSubstance implements InchFinder {

  public void foundInchi(String myInchi, Map<java.lang.Object, java.lang.Object> objectObjectMap) throws Exception {
    Logger logger = Logger.getLogger("ImportNCI")

    NCIDBSDFResolver resolver = new NCIDBSDFResolver();
    resolver.prepare(objectObjectMap)

    Compound compound = CompoundHelper.getCompound(resolver.getInchi(),resolver.getInchiKey(),logger)

    //adding the cas number
    CompoundHelper.updatesTheCasNumber(resolver.getCas(), compound, logger)

    CompoundHelper.updateNCI(logger,compound,resolver.getId())
    generateSynonyms(resolver, logger, compound)

    //save the compound again
    compound = CompoundHelper.saveCompound(compound, logger)


    CompoundHelper.aquireStatistic()
  }

  private void generateSynonyms(NCIDBSDFResolver resolver, Logger logger, Compound compound) {
    if (resolver.getNames() != null) {
      logger.debug "store synonyms"
      //work on iupac names
      List<String> syn = new Vector<String>()

      for (String s: resolver.getNames()) {
        if (s != null) {
          s = s.replaceAll("\\(ACD/Name\\)", "").trim()
          if (!syn.contains(s)) {
            syn.add(s)
          }
        }
      }

      if (!syn.isEmpty()) {
        CompoundHelper.addSynonym(syn, logger, compound)
      }
      else {
        logger.info "no synonyms were found!"
      }
    }
    else {
      logger.debug "no names defined"
    }

    if (resolver.getName() != null) {
      logger.debug "store primary name as synonym"
      //work on iupac names
      List<String> syn = new Vector<String>()
      syn.add(resolver.getName().replaceAll("\\(ACD/Name\\)", ""))
      CompoundHelper.addSynonym(syn, logger, compound)
    }
    else {
      logger.debug "no primary name defined"
    }
  }

}